package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.system.domain.ArchiveLocation;
import com.ruoyi.system.domain.ArchiveStrategy;
import com.ruoyi.system.domain.bo.ArchiveStrategyBo;
import com.ruoyi.system.domain.vo.ArchiveStrategyVo;
import com.ruoyi.system.enums.ArchiveStrategyTypeEnum;
import com.ruoyi.system.mapper.ArchiveLocationMapper;
import com.ruoyi.system.mapper.ArchiveStrategyMapper;
import com.ruoyi.system.service.IArchiveStrategyService;
import com.ruoyi.system.util.ArchiveUtil;
import com.ruoyi.system.util.Constants;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 归档策略Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-06
 */
@RequiredArgsConstructor
@Service
public class ArchiveStrategyServiceImpl implements IArchiveStrategyService {

    private final ArchiveStrategyMapper baseMapper;

    private final ArchiveLocationMapper locationMapper;

    private final ArchiveStrategyMapper strategyMapper;

    /**
     * 查询归档策略
     */
    @Override
    public ArchiveStrategyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询归档策略列表
     */
    @Override
    public TableDataInfo<ArchiveStrategyVo> queryPageList(ArchiveStrategyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ArchiveStrategy> lqw = buildQueryWrapper(bo);
        Page<ArchiveStrategyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtils.isNotEmpty(result.getRecords())) {
            List<Long> locationIds = result.getRecords().stream().map(t -> t.getLocationId()).collect(Collectors.toList());
            Map<Long, String> locationNameMap = locationMapper.selectBatchIds(locationIds).stream().collect(Collectors.toMap(k -> k.getId(), k -> k.getName()));
            for (ArchiveStrategyVo strategyVo : result.getRecords()) {
                strategyVo.setLocationName(locationNameMap.get(strategyVo.getLocationId()));
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询归档策略列表
     */
    @Override
    public List<ArchiveStrategyVo> queryList(ArchiveStrategyBo bo) {
        LambdaQueryWrapper<ArchiveStrategy> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ArchiveStrategy> buildQueryWrapper(ArchiveStrategyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ArchiveStrategy> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), ArchiveStrategy::getName, bo.getName());
        lqw.eq(bo.getStrategyType() != null, ArchiveStrategy::getStrategyType, bo.getStrategyType());
        lqw.eq(bo.getPubStatus() != null, ArchiveStrategy::getPubStatus, bo.getPubStatus());
        return lqw;
    }

    /**
     * 新增归档策略
     */
    @Override
    public Boolean insertByBo(ArchiveStrategyBo bo) {
        ArchiveStrategy add = BeanUtil.toBean(bo, ArchiveStrategy.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改归档策略
     */
    @Override
    public Boolean updateByBo(ArchiveStrategyBo bo) {
        ArchiveStrategy update = BeanUtil.toBean(bo, ArchiveStrategy.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ArchiveStrategy strategy) {
        //TODO 做一些数据校验,如唯一约束
        ArchiveLocation location = locationMapper.selectById(strategy.getLocationId());
        if (location == null) {
            throw new ServiceException("归档位置不存在");
        }
        ArchiveUtil.checkLocation(location);

        if (ArchiveStrategyTypeEnum.COMPRESS_TABLE.getValue() != strategy.getStrategyType()) {
            return;
        }
        //压缩表，备份到数据库
        checkDb(strategy, location);
    }

    private void checkDb(ArchiveStrategy strategy, ArchiveLocation location) {
        List<String> targetCells = Arrays.asList(strategy.getTargetFields().split(Constants.COMMA));
        String checkSql = ArchiveUtil.getCheckSql(strategy.getTargetTable(), targetCells);
        try (Connection connection = ArchiveUtil.getDbConnection(location)) {
            try (PreparedStatement statement = connection.prepareStatement(checkSql)) {
                statement.execute();
            }
        } catch (Exception e) {
            throw new ServiceException("数据库校验失败，请确认目标表、字段是否正确");
        }
    }

    /**
     * 批量删除归档策略
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List getConfig() {
        List<Map> list = strategyMapper.getConfig();
        if (list != null) {
            for (Map map : list) {
                map.put("config", JSON.parseObject(map.get("config").toString()));
            }
        }
        return list;
    }

    @Override
    public Boolean checkStrategy(ArchiveStrategyBo bo) {
        ArchiveStrategy update = BeanUtil.toBean(bo, ArchiveStrategy.class);
        validEntityBeforeSave(update);
        return Boolean.TRUE;
    }
}
